package com.lzh.dlykserver.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lzh.dlykserver.constant.Constants;
import com.lzh.dlykserver.entity.TPermission;
import com.lzh.dlykserver.entity.TRole;
import com.lzh.dlykserver.entity.TUser;
import com.lzh.dlykserver.manager.RedisManager;
import com.lzh.dlykserver.mapper.TPermissionMapper;
import com.lzh.dlykserver.mapper.TRoleMapper;
import com.lzh.dlykserver.mapper.TUserMapper;
import com.lzh.dlykserver.query.BaseQuery;
import com.lzh.dlykserver.query.PwdDTO;
import com.lzh.dlykserver.query.UserQuery;
import com.lzh.dlykserver.service.UserService;
import com.lzh.dlykserver.util.CacheUtils;
import com.lzh.dlykserver.util.JWTUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private RedisManager redisManager;

    @Resource
    private TUserMapper tUserMapper;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private TRoleMapper tRoleMapper;

    @Resource
    private TPermissionMapper tPermissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TUser tUser = tUserMapper.selectByLoginAct(username);
        if (tUser == null) {
            throw new UsernameNotFoundException("登录账号不存在！");
        }

        //查询用户的角色
        List<TRole> tRoleList = tRoleMapper.selectByUserId(tUser.getId());

        //字符串角色列表
        List<String> stringsRoleList = new ArrayList<>();
        tRoleList.forEach(tRole -> {
            stringsRoleList.add(tRole.getRole());
        });

        //设置用户的角色
        tUser.setRoleList(stringsRoleList);

        //查询该用户有哪些菜单权限
        List<TPermission> menuPermission = tPermissionMapper.selectMenuPermissionByUserId(tUser.getId());
        tUser.setMenuPermissionList(menuPermission);

        //查询一下该用户有哪些功能
        List<TPermission> buttonPermissionList = tPermissionMapper.selectButtonPermissionByUserId(tUser.getId());
        List<String> stringPermissionList = new ArrayList<>();
        buttonPermissionList.forEach(tPermission -> {
            stringPermissionList.add(tPermission.getCode());    //权限标识符
        });
        tUser.setPermissionList(stringPermissionList);


        return tUser;
    }

    @Override
    public PageInfo<TUser> getUserByPage(Integer current) {
        //设置PageHelper
        PageHelper.startPage(current, Constants.PAGE_SIZE);
        //查询
        List<TUser> list = tUserMapper.selectUserByPage(BaseQuery.builder().build());
        //封装分页数据到PageInfo
        PageInfo<TUser> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public TUser getUserById(Integer id) {
        return tUserMapper.selectDetailByPrimaryKey(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int saveUser(UserQuery usrQuery) {
        TUser tUser = new TUser();

        //把userQuery中的属性复制到tUser中(复制要求，两个对象的属性名相同，类型相同)
        BeanUtils.copyProperties(usrQuery, tUser);
        //密码加密
        tUser.setLoginPwd(passwordEncoder.encode(tUser.getLoginPwd()));

        //创建时间
        tUser.setCreateTime(new Date());
        //创建人id
        Integer loginUserId = JWTUtils.parseUserFromJWT(usrQuery.getToken()).getId();
        tUser.setCreateBy(loginUserId);

        return tUserMapper.insertSelective(tUser);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateUser(UserQuery usrQuery) {
        TUser tUser = new TUser();

        //把userQuery中的属性复制到tUser中(复制要求，两个对象的属性名相同，类型相同)
        BeanUtils.copyProperties(usrQuery, tUser);

        if (StringUtils.hasText(usrQuery.getLoginPwd())) {
            //密码加密
            tUser.setLoginPwd(passwordEncoder.encode(tUser.getLoginPwd()));
        }

        //编辑时间
        tUser.setEditTime(new Date());
        //编辑人id
        Integer editUserId = JWTUtils.parseUserFromJWT(usrQuery.getToken()).getId();
        tUser.setCreateBy(editUserId);

        return tUserMapper.updateByPrimaryKeySelective(tUser);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteUser(Integer id) {
        return tUserMapper.deleteByPrimaryKey(id);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public int batchDeleteUser(List<String> idList) {
        return tUserMapper.deleteByIds(idList);
    }

    @Override
    public List<TUser> getOwnerList() {
        //1.从redis查询
        //2.若redis查不到，就从数据库查，并把数据放入redis(5分钟过期)
        return CacheUtils.getCacheData(
                () -> {
                    //生产，从redis查询数据
                    return (List<TUser>) redisManager.getValue(Constants.REDIS_OWNER_KEY);
                },
                () -> {
                    //生产，从数据库查
                    return tUserMapper.selectOwner();
                },
                (t) -> {
                    //消费，把数据放入redis
                    redisManager.setValue(Constants.REDIS_OWNER_KEY, t);
                });
    }

    @Override
    public int changePassword(PwdDTO pwdDTO) {
        TUser tUser = new TUser();
        tUser.setLoginPwd(pwdDTO.getNewPassword());
        tUser.setId(pwdDTO.getUserId());

        //密码加密
        tUser.setLoginPwd(passwordEncoder.encode(tUser.getLoginPwd()));

        Integer loginId = JWTUtils.parseUserFromJWT(pwdDTO.getToken()).getId();
        tUser.setEditBy(loginId);
        tUser.setEditTime(new Date());
        return tUserMapper.updateByPrimaryKeySelective(tUser);
    }

}
